<template>
  <div class="relative page-container give-car-wrapper">
    <div class="page-form-block">
      <!-- 统计 -->
      <summary-info :summaryList="summaryLease" />
      <a-divider />
      <summary-info :summaryList="summaryCarInfo" />
    </div>
    <a-divider />
    <page-form :model="form" layout="vertical" :rules="rules" ref="formRef">
      <card title="还车信息" style="margin-top: 20px">
        <box-info :carId="orderInfo.carId" style="margin-bottom: 20px" />
        <page-form-row>
          <page-form-item label="还车里程" field="endCarMileage">
            <i-input-number
              :precision="0"
              :min="prevGivecarMileage ? prevGivecarMileage : undefined"
              unit="公里"
              v-model="form.endCarMileage"
              @change="endCarMileChangeFn"
            />
          </page-form-item>
          <page-form-item label="还车油(电)量" field="endCarOil">
            <i-input-number :precision="0" :min="1" :max="99999" unit="" v-model="form.endCarOil" />
          </page-form-item>
          <page-form-item field="returnStaffId" label="还车人">
            <remote-select
              v-model="form.returnStaffId"
              :params="{
                oldId: defaultStaffId ? defaultStaffId : undefined,
                siteIdList: [orderInfo.returnSiteId],
              }"
              type="staff_authOrg"
            />
          </page-form-item>
          <page-form-item field="useEndTime" label="还车时间">
            <i-date-picker
              :allow-clear="false"
              class="w-full"
              v-model="form.useEndTime"
              format="YYYY-MM-DD HH:mm"
              valueFormat="YYYY-MM-DD HH:mm:00"
              :disabled-date="disabledDate"
              :disabled-time="disabledTime"
              :time-picker-props="{
                format: 'HH:mm',
                defaultValue: '00:00',
              }"
              showTime
              @change="useEndTimeChangeFn"
            />
          </page-form-item>
          <page-form-item label="还车备注" size="2/3">
            <i-textarea v-model="form.useEndRemark" />
          </page-form-item>
          <page-form-item field="returnMilesFileId" label="还车里程/油(电)量照片" size="1">
            <upload-img v-model="form.returnMilesFileId" :limit="1" />
          </page-form-item>
          <page-form-item field="fileIds" label="还车照片" size="1">
            <upload-img v-model="form.fileIds" />
          </page-form-item>
          <page-form-item label="还车视频" size="1" class="mb-0">
            <upload-video v-model="form.videoFileIds" :max="1" />
          </page-form-item>
        </page-form-row>
      </card>
      <!-- 费用信息 -->
      <div class="relative fee-pane-content">
        <page-form :model="feeForm" ref="feeFormRef" layout="vertical">
          <card toggle :showDivider="false">
            <template #title>还车费用</template>
            <div class="mb-4" v-if="orderInfo?.channelType == -3 && orderInfo?.channelOrderMaintenance == 1">
              <a-alert>如需添加线上费用，请先前往铁行平台进行添加，完成添加后，会自动同步至启程平台的此订单中。</a-alert>
            </div>
            <template v-for="(item, index) in feeForm.orderFee" :key="index">
              <fee-pane
                :orderFeeIndex="index"
                :disabledOnlineFee="orderInfo.orderSource == 1 || (orderInfo?.channelType == -3 && orderInfo?.channelOrderMaintenance == 1)"
                fromPage="returnCar"
              >
                <template #returnDepositFee="{ feeOption, showDivider }">
                  <card :title="feeOption.feeName" :showDivider="showDivider">
                    <return-deposit :orderId="orderInfo.id" />
                  </card>
                </template>
              </fee-pane>
            </template>
          </card>
        </page-form>
      </div>
    </page-form>
  </div>
  <!-- 底部 footer -->
  <page-form-footer hideCancel hideOk>
    <a-button @click="newRepairFn">新增维修信息</a-button>
    <a-button @click="newViolationFn">新增违章信息</a-button>
    <a-button @click="cancelFn">关闭</a-button>
    <a-button type="primary" :loading="okLoading" @click="submitFn">确认</a-button>
  </page-form-footer>
  <!-- 查询当前订单的还车车辆是否存在与当前订单关联的状态为已开始的ETC订单 -->
  <finishEtcOrderModal ref="etcModalRef" @ok="submitOperateFn" />
</template>
<script setup name="ShortOrderReturnCar">
  import finishEtcOrderModal from '../etc-order/components/finish-etc-order-modal.vue'
  import feePane from './components/order-fee/fee-pane.vue'
  import iTextarea from '@/views/order/short-order/components/i-textarea.vue'
  import summaryInfo from './components/summary-info.vue'
  import boxInfo from '../../business/workOrder/order/components/box-modal.vue'
  import returnDeposit from './components/return-car/return-deposit.vue'

  import { getShortOrdrDetails, returnCar, calcPrice } from '@/api/order/sOrder'
  import { checkExistEtcOrderApi } from '@/api/order/etcOrder'
  import { buildCostInfoParam, initFeeDetail, getStoreTemplateDetail } from './components/order-fee/fee-utils.js'
  import useUserStore from '@/store/modules/user'
  import useNavigate from '@/hooks/useNavigate'

  import { ref, provide, computed, reactive } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { Message, Notification } from '@arco-design/web-vue'
  import dayjs from 'dayjs'

  const { navigateBack, navigateClose } = useNavigate()
  import { orderIsTiexing } from './utils.js'
  // 订单拦截hooks
  import useOrderIntercept from './hooks/useTieXingInterceptor'
  const userStore = useUserStore()
  const route = useRoute()
  const router = useRouter()
  const orderId = route.params.id
  const orderInfo = ref({})
  provide('addFeeOrderInfo', orderInfo)
  const memberInfo = ref({})

  const form = ref({
    id: orderId,
    useEndTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    depositDeductFlag: 0,
    changeDepositFlag: 0,
  })
  // 处理默认值
  const rules = reactive({
    returnStaffId: [{ required: true, message: '请选择还车人' }],
    useEndTime: [{ required: true, message: '请选择还车时间' }],
    endCarMileage: [{ required: true, message: '请输入还车里程' }], // 还车里程
    endCarOil: [{ required: true, message: '请输入还车油(电)量' }], // 还车油(电)量
  })
  const formRef = ref()
  provide('form', form)

  const priceTemplateId = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['extraFee', 'refuseFee'],
      },
    ],
  })
  provide('feeForm', feeForm)

  const prevGivecarMileage = computed(() => {
    let shortOrderCarInfoDtos = orderInfo.value.shortOrderCarInfoDtos
    if (shortOrderCarInfoDtos && shortOrderCarInfoDtos.length) {
      return shortOrderCarInfoDtos[shortOrderCarInfoDtos.length - 1].startCarMileage
    }
    return null
  })
  const prevGivecarTime = computed(() => {
    let shortOrderCarInfoDtos = orderInfo.value.shortOrderCarInfoDtos
    if (shortOrderCarInfoDtos && shortOrderCarInfoDtos.length) {
      return shortOrderCarInfoDtos[shortOrderCarInfoDtos.length - 1].useStartTime
    }
    return null
  })
  // disabled Date|Time
  const disabledDate = (dateVal) => {
    const prevDate = prevGivecarTime.value
    if (!dateVal || !prevDate) {
      return false
    }
    // 存在限制最大范围
    // 当前时间是 23:50
    if (dayjs(prevDate).hour() == 23 && dayjs(prevDate).minute() == 59) {
      return dayjs(prevDate).add(1, 'd').startOf('day').valueOf() > dayjs(dateVal).valueOf()
    } else {
      return dayjs(prevDate).startOf('day').valueOf() > dayjs(dateVal).valueOf()
    }
  }
  const range = (start, end) => {
    const result = []
    for (let i = start; i < end; i++) {
      result.push(i)
    }
    return result
  }
  const disabledTime = (current) => {
    let options = {}
    const prevDate = prevGivecarTime.value
    if (prevDate) {
      let currentTime = current ? dayjs(current) : dayjs()
      let currentTime_year = currentTime.year()
      let currentTime_month = currentTime.month()
      let currentTime_date = currentTime.date()
      let currentTime_hour = currentTime.hour()
      let prevDateTime = dayjs(prevDate)
      let prevDateTime_year = prevDateTime.year()
      let prevDateTime_month = prevDateTime.month()
      let prevDateTime_date = prevDateTime.date()
      let prevDateTime_hour = prevDateTime.hour()
      let prevDateTime_minute = prevDateTime.minute()
      if (prevDateTime_minute == 59) {
        options.disabledHours = () => range(0, prevDateTime_hour + 1)
        options.disabledMinutes = () => []
      } else {
        options.disabledHours = () => range(0, prevDateTime_hour)
        options.disabledMinutes = () => range(0, prevDateTime_minute + 1)
      }
      // 用户选择的是 未来 的天
      if (currentTime_year > prevDateTime_year || currentTime_month > prevDateTime_month || currentTime_date > prevDateTime_date) {
        options = {}
      } else {
        // 用户选择的是 未来 的小时
        if (currentTime_hour > prevDateTime_hour) {
          options.disabledMinutes = () => {
            return []
          }
        }
      }
    }
    return options
  }
  // 默认员工
  const defaultStaffId = ref()
  if (orderId) {
    getShortOrdrDetails({ id: orderId }).then((res) => {
      const result = res.result
      orderInfo.value = result.orderInfo
      memberInfo.value = result.memberInfoDto
      // 处理默认值
      // 车务专员 | 当前登录者 id
      defaultStaffId.value = orderInfo.value.returnStaffId || userStore.employeeId
      // 默认还车人
      form.value.returnStaffId = defaultStaffId.value
      // 读取门店模板配置
      getStoreTemplateDetail(orderInfo.value.siteId, 1, (storeTemplate, templateId) => {
        // 初始化费用
        initFeeDetail(feeForm.value, storeTemplate)
        // 更新费用模板 id
        priceTemplateId.value = templateId
        // 初始化 超里程费和超时费
        calcDefaultFee('useEndTime')
      })
      // 自动维护的铁行渠道订单逻辑处理
      updateTiexingStore()
    })
  }
  const updateTiexingStore = () => {
    // 针对自动维护的铁行渠道订单，将交车照片字段变为必填项
    if (orderIsTiexing(orderInfo.value)) {
      Object.assign(rules, {
        fileIds: [{ required: true, message: '请上传还车照片' }], // 还车照片
        returnMilesFileId: [{ required: true, message: '请上传还车里程/油(电)量照片' }], // 还车里程/油电量照片
      })
    }
  }
  // 还车里程变更
  const endCarMileChangeFn = () => {
    calcDefaultFee('endCarMile')
  }
  // 还车时间变更
  const useEndTimeChangeFn = () => {
    calcDefaultFee('useEndTime')
  }
  // 计算默认费用
  const calcDefaultFee = (type) => {
    const param = {
      endTime: form.value.useEndTime,
      endCarMileage: form.value.endCarMileage,
      id: form.value.id,
      siteId: orderInfo.value.siteId,
      modelId: orderInfo.value.originalModelId,
      type: 2,
    }
    calcPrice(param).then((res) => {
      const result = res.result
      const otherPrice = result.otherPrice
      if (otherPrice) {
        let feeDetailList = feeForm.value.orderFee[0].feeDetailList
        feeDetailList.forEach((feeCategory) => {
          if (feeCategory.type == 'extraFee') {
            let childrenList = feeCategory.childrenList
            childrenList.forEach((feeItem) => {
              if (feeItem.itemName == '超里程费') {
                if (type == 'endCarMile') {
                  let defaultFee = otherPrice.find((item) => item.itemName == '超里程费')
                  if (defaultFee) {
                    feeItem.amount = defaultFee.amount
                  }
                }
              }
              if (feeItem.itemName == '超时费') {
                if (type == 'useEndTime') {
                  let defaultFee = otherPrice.find((item) => item.itemName == '超时费')
                  if (defaultFee) {
                    feeItem.amount = defaultFee.amount
                  }
                }
              }
            })
          }
        })
      }
    })
  }

  const okLoading = ref(false)
  // 表单提交操作
  const submitOperateFn = () => {
    let feeFormValue = feeForm.value
    let costInfo = buildCostInfoParam(feeFormValue)

    // 还车已结算费用特殊，跟添加用户缴费数据格式不一样，需要将已结算费用单独提出
    let settledFeeList = []
    costInfo.orderFee[0]?.feeDetailList?.forEach((feeItem) => {
      if (feeItem.feeCategory == 5) {
        costInfo.orderFee[0].feeDetailList.push({
          childrenList: [],
          compensateReason: feeItem.compensateReason,
          feeCategory: 12,
          feeNameId: feeItem.feeNameId,
          id: feeItem.id,
          remark: feeItem.remark,
          type: feeItem.type,
        })

        settledFeeList = feeItem.childrenList.filter((childItem) => childItem.feeCategory == 12)
        feeItem.childrenList = feeItem.childrenList.filter((childItem) => childItem.feeCategory != 12)
      }
    })
    costInfo.orderFee[0]?.feeDetailList?.forEach((feeItem) => {
      if (feeItem.feeCategory == 12) {
        feeItem.childrenList = settledFeeList
      }
    })

    const param = {
      ...form.value,
      orderFee: costInfo.orderFee[0],
    }
    okLoading.value = true
    returnCar(param)
      .then(({ result }) => {
        // 调用铁行接口失败：false
        if (result && result.success == false) {
          return useOrderIntercept(orderInfo.value, 'returnCarSubmit', () => {
            navigateBack()
          })
        }
        Notification.success({
          content: '保存成功',
          closable: true,
          duration: 3000,
        })
        navigateBack()
      })
      .finally(() => (okLoading.value = false))
  }
  // 检验还车车辆是否存在与当前订单关联的状态为已开始的ETC订单
  const etcModalRef = ref()
  const submitFn = () => {
    formRef.value.validate((error) => {
      if (!error) {
        let params = {
          refType: 1,
          refId: form.value.id,
          carId: orderInfo.value.carId,
          endTime: form.value.useEndTime,
        }
        checkExistEtcOrderApi(params).then((res) => {
          let result = res.result
          if (result.existOrder) {
            let params = {
              carLicenseNo: orderInfo.value.carLicenseNo,
              operateStr: '还车',
            }
            etcModalRef.value.open(params)
          } else {
            submitOperateFn()
          }
        })
      }
    })
  }
  const newRepairFn = () => {
    if (orderInfo.value.carId) {
      router.push(`/car-repair/create/${orderId}?page=shortOrder`)
    } else {
      Message.error('当前车辆为渠道车辆，请先同平台车辆匹配后再创建运维订单')
    }
  }
  const newViolationFn = () => {
    if (orderInfo.value.carId) {
      router.push(`/car-violation/create/${orderId}?page=shortOrder`)
    } else {
      Message.error('当前车辆为渠道车辆，请先同平台车辆匹配后再创建运维订单')
    }
  }
  const cancelFn = () => {
    navigateClose()
  }

  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      [
        {
          label: '预计租赁周期',
          value: orderInfoVal.startTime ? `${orderInfoVal.startTime} - ${orderInfoVal.endTime}` : '-',
        },
        { label: '租期', value: orderInfoVal.rentDays },
        { label: '订单来源', value: orderInfoVal.orderSourceName },
      ],
      [
        { label: '订单获取方式', value: orderInfoVal.orderAcquisitionTypeName },
        { label: '车型', value: orderInfoVal.originalModelName },
        { label: '交车车型', value: orderInfoVal.carModelName },
      ],
      [{ label: '交车车牌号', value: orderInfoVal.carLicenseNo }],
    ]
  })

  const summaryCarInfo = computed(() => {
    const orderCarInfos = orderInfo.value.shortOrderCarInfoDtos
    let lastOrderCarInfo = {}
    if (orderCarInfos && orderCarInfos.length > 0) {
      lastOrderCarInfo = orderCarInfos[orderCarInfos.length - 1]
    }
    return [
      [
        {
          label: '交车里程',
          value: lastOrderCarInfo.startCarMileage ? lastOrderCarInfo.startCarMileage + ' 公里' : '',
        },
        { label: '交车油(电)量', value: lastOrderCarInfo.startCarOil ? lastOrderCarInfo.startCarOil : '' },
      ],
    ]
  })
</script>
<style lang="less" scoped></style>
